import { onMounted, reactive } from 'vue'
import { format } from 'date-fns'
import { parseTime } from '@/common/common'
import { UdfDefined } from '@/service/modules/task-manage/types'
import { delUdfReq, findUdfsReq } from '@/service/modules/task-manage'

export function useTable() {
  const state = reactive({
    name: '',
    dbType: null,
    list: [],
    loading: false,
    currentRecord: {} as UdfDefined,
    showModUDFModalRef: false,
    showUDFDetailModalRef: false
  })

  const getList = async () => {
    state.loading = true
    const res = await findUdfsReq({ dbType: state.dbType, name: state.name })
    state.loading = false
    if (!res.data) throw Error()
    state.list = res.data.map((record: UdfDefined) => {
      record.createTime = record.createTime
        ? format(parseTime(record.createTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      record.updateTime = record.updateTime
        ? format(parseTime(record.updateTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      return record
    })
  }

  const delUdf = (id: number, name: string) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('taskManage.delUdfTips') + name,
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delUdfReq({ id: id })
        if (res.resp_code === 0) {
          getList()
        }
      }
    })
  }
  const onOperationClick = (
    data: { rowData: UdfDefined },
    type: 'delUdf' | 'showUdfDetail' | 'modUdf'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'delUdf':
        delUdf(data.rowData.id, data.rowData.name)
        break
      case 'showUdfDetail':
        state.showUDFDetailModalRef = true
        break
      case 'modUdf':
        state.showModUDFModalRef = true
        break
    }
  }

  onMounted(() => {
    getList()
  })

  return {
    state,
    onOperationClick,
    getList
  }
}
